<?php
/**
 * 体检中心接口数据同步
 *
 * User: kaikaic
 * Date: 2018/11/15
 * Time: 22:16
 */

namespace app\exam\model;

use app\exam\service\SyncService;
use think\Db;

class SyncMecModel {

    // 接口地址
    const SYNC_URL_MEC = "http://192.168.0.104/api";

    // 接口方法-体检中心
    const SYNC_URL_API_MEC = "/sync/mec";

    // 接口方法-体检套餐
    const SYNC_URL_API_SET = "/set";

    // 接口KEY
    const API_KEY = "98302432";

    // 接口密钥
    const API_SECRET = "ewquroewuqo234ouew";

    public function __construct() {

    }

    public static function getSyncUrl() {
        return self::SYNC_URL_MEC;
    }

    /**
     * 同步体检中心数据
     */
    public function syncMec() {
        $url = $this->createSignedUrl(self::SYNC_URL_MEC . self::SYNC_URL_API_MEC);
        $response = $this->sendSyncRequest($url);

        return SyncService::getInstance()->updateMec($response);
    }

    /**
     * 同步体检中心-体检套餐数据
     */
    public function syncMecSet() {
        $url = $this->createSignedUrl(self::SYNC_URL_MEC . self::SYNC_URL_API_SET);
        $response = $this->sendSyncRequest($url);

        return SyncService::getInstance()->updateMecSet($response);
    }

    /**
     * 生成签名地址
     * @param $url
     * @return string
     */
    private function createSignedUrl($url) {
        //TODO 地址签名方法
        $signedUrl = $url . "";

        return $signedUrl;
    }

    /**
     * 同步数据
     * @param $url
     * @return mixed
     */
    private function sendSyncRequest($url, $data="") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);

        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        //设置头部信息
        $headers = array('Content-Type:application/json; charset=utf-8','Content-Length: '.strlen($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);

        //执行请求
        $output = curl_exec($ch);
        if($output === FALSE ) {
//            echo "CURL Error:" . curl_error($ch);
            return array();
        }

        return json_decode($output, true);
    }
}

